package inet.app.view.activity;

import inet.app.R;
import inet.app.common.XoSoConstants;
import inet.app.controller.connect.JsonParser;
import inet.app.controller.parser.Parser_Tk;
import inet.app.controller.request.Request;
import inet.app.model.object.Tk_Item;
import inet.app.model.util.MyPreferenceManager;
import inet.app.model.util.SmartLog;
import inet.app.model.util.Util;
import inet.app.view.adapter.KetQuaDetailAdapter;
import inet.app.view.fragment.FragmentTKDB;
import inet.app.view.fragment.FragmentTKN;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class ThongKeFragment extends BaseFragmentActivity implements
		OnClickListener {
	private ViewPager _mViewPager;
	private KetQuaDetailAdapter _adapter;
	private FragmentTKDB ftkdb;
	Spinner sptinh;
	private FragmentTKN ftkn;
	int Yellow1 = Color.rgb(255, 255, 0);
	int Red1 = Color.rgb(255, 0, 0);
	int heavyblue = Color.rgb(0, 0, 255);
	private ArrayList<Fragment> list_Fragment;
	public int posCurrent = 1;
	Dialog about, help, dialog, dlquit;
	int demtrang = 1;
	int max = 10;
	private LinearLayout first_text, second_text;
	private TextView tvTitle, tvNhamang;
	ArrayList<Tk_Item> arraylist = new ArrayList<Tk_Item>();
	private Request request = new Request();
	private String[] list_tinh = new String[] { "Thủ Đô", "TP HCM", "An Giang",
			"Bình Dương", "Bình Phước", "Bạc Liêu", "Bến Tre", "Cà Mau",
			"Cần Thơ", "Hậu Giang", "Kiên Giang", "Long An", "Sóc Trăng",
			"Tiền Giang", "Trà Vinh", "Tây Ninh", "Vĩnh Long", "Vũng Tàu",
			"Đà Lạt", "Đồng Nai", "Đồng Tháp", "Bình Thuận", "Bình Định",
			"Đắk Lắk", "Gia Lai", "Khánh Hòa", "Kon Tum", "Ninh Thuận",
			"Phú Yên", "Quảng Bình", "Quảng Nam", "Quảng Ngãi", "Quảng Trị",
			"Thừa Thiên Huế", "Đà Nẵng", "Đắc Nông" };
	String[] list_tkdb = new String[] { "Đầu", "Đuôi", "Tổng", "Bộ" };
	private String selectTKDB, select;

	private TextView tvSpTinh;
	private String name = "Thủ Đô", matinh = "XSTD";
	private MyPreferenceManager mPreference;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.thongke_fragment);
		initBase();
		initUI();
		initFragment();
		init_ViewPager();
		setTab();
	}

	private void initUI() {

		first_text = (LinearLayout) findViewById(R.id.first_text);
		second_text = (LinearLayout) findViewById(R.id.second_text);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvNhamang = (TextView) findViewById(R.id.tvNhamang);
		tvNhamang.setText(Util.getSharePreferences(ThongKeFragment.this));
		first_text.setOnClickListener(this);
		second_text.setOnClickListener(this);
		sptinh = (Spinner) findViewById(R.id.sptinh);
		tvSpTinh = (TextView) findViewById(R.id.tvSpTinh);
		tvSpTinh.setOnClickListener(this);
		AddSpinnerTinh();
		_mViewPager = (ViewPager) findViewById(R.id.viewPager);
		list_Fragment = new ArrayList<Fragment>();
		mPreference = MyPreferenceManager.getInstance(this);
	}

	public void AddSpinnerTinh() {

		// Add Data Spinner
		ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(
				ThongKeFragment.this, android.R.layout.simple_spinner_item,
				list_tinh);
		arrayadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sptinh.setAdapter(arrayadapter);
		sptinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				sptinh.setSelection(pos);
				tvSpTinh.setText(" " + list_tinh[pos]);
				switch (pos) {
				case 0:
					name = "Thủ Đô";
					matinh = "XSTD";
					break;
				case 1:
					name = "TP HCM";
					matinh = "XSHCM";
					break;
				case 2:
					matinh = "XSAG";
					name = "An Giang";
					break;
				case 3:
					matinh = "XSBD";
					name = "Bình Dương";
					break;
				case 4:
					matinh = "XSBP";
					name = "Bình Phước";
					break;
				case 5:
					matinh = "XSBL";
					name = "Bạc Liêu";
					break;
				case 6:
					matinh = "XSBT";
					name = "Bến Tre";
					break;
				case 7:
					matinh = "XSCM";
					name = "Cà Mau";
					break;
				case 8:
					matinh = "XSCT";
					name = "Cần Thơ";
					break;
				case 9:
					matinh = "XSHG";
					name = "Hậu Giang";
					break;
				case 10:
					matinh = "XSKG";
					name = "Kiên Giang";
					break;
				case 11:
					matinh = "XSLA";
					name = "Long An";
					break;
				case 12:
					matinh = "XSST";
					name = "Sóc Trăng";
					break;
				case 13:
					matinh = "XSTG";
					name = "Tiền Giang";
					break;
				case 14:
					matinh = "XSTV";
					name = "Trà Vinh";
					break;
				case 15:
					matinh = "XSTN";
					name = "Tây Ninh";
					break;
				case 16:
					matinh = "XSVL";
					name = "Vĩnh Long";
					break;
				case 17:
					matinh = "XSVT";
					name = "Vũng Tàu";
					break;
				case 18:
					matinh = "XSDL";
					name = "Đà Lạt";
					break;
				case 19:
					matinh = "XSDN";
					name = "Đông Nai";
					break;
				case 20:
					matinh = "XSDT";
					name = "Đồng Tháp";
					break;
				case 21:
					matinh = "XSBTH";
					name = "Bình Thuận";
					break;
				case 22:
					matinh = "XSBDH";
					name = "Bình Định";
					break;
				case 23:
					matinh = "XSDLK";
					name = "Đăk Lăk";
					break;
				case 24:
					matinh = "XSGL";
					name = "Gia Lai";
					break;
				case 25:
					matinh = "XSKH";
					name = "Khánh Hòa";
					break;
				case 26:
					matinh = "XSKT";
					name = "Kon Tum";
					break;
				case 27:
					matinh = "XSNT";
					name = "Ninh Thuận";
					break;
				case 28:
					matinh = "XSPY";
					name = "Phú Yên";
					break;
				case 29:
					matinh = "XSQB";
					name = "Quảng Bình";
					break;
				case 30:
					matinh = "XSQNM";
					name = "Quảng Nam";
					break;
				case 31:
					matinh = "XSQNI";
					name = "Quảng Ngãi";
					break;
				case 32:
					matinh = "XSQT";
					name = "Quảng Trị";
					break;
				case 33:
					matinh = "XSTTH";
					name = "Thừa Thiên Huế";
					break;
				case 34:
					matinh = "XSDNG";
					name = "Đà Nẵng";
					break;
				case 35:
					matinh = "XSDNO";
					name = "Đắc Nông";
					break;
				}
				((MyApp) getApplication()).setCode(matinh);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	public void AddSpinnerTk() {

		// SP Thống kê đặc biệt
		ArrayAdapter<String> arrayadapter_tkdb = new ArrayAdapter<String>(
				ThongKeFragment.this, android.R.layout.simple_spinner_item,
				list_tkdb);
		arrayadapter_tkdb
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sptinh.setAdapter(arrayadapter_tkdb);
		sptinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				sptinh.setSelection(pos);
				switch (pos) {
				case 0:
					selectTKDB = "Đầu";
					select = "DAU";
					break;
				case 1:
					selectTKDB = "Đuôi";
					select = "DUOI";
					break;
				case 2:
					selectTKDB = "Tổng";
					select = "TONG";
					break;
				case 3:
					selectTKDB = "Bộ";
					select = "BO";
					break;
				default:
					break;
				}
				((MyApp) getApplication()).setSelectCode(select);
				((MyApp) getApplication()).setSelectName(selectTKDB);
				tvSpTinh.setText(selectTKDB);
				pdia.show();
				boolean isFoundPreference = false;
				if (mPreference.isLoadTKDB(select)) {
					String json = mPreference.getContentTKDB(select);
					if (!TextUtils.isEmpty(json)) {
						SmartLog.d("load " + select + " date " + date_current
								+ " from preference");
						isFoundPreference = true;
						fillJsonToView(json);
					}
				}
				if (!isFoundPreference) {
					// load from server
					final Handler handler = new Handler() {
						@Override
						public void handleMessage(Message msg) {

							super.handleMessage(msg);
							pdia.dismiss();

							if (msg.what == 0) {
								SmartLog.d("load " + select + " date "
										+ date_current + " from server");
								String json = (String) msg.obj;
								mPreference.setContentTKDB(select, json);
								mPreference.setLoadTKDB(select, true);
								fillJsonToView(json);
							} else if (msg.what == 1) {
								Util.showDialog(1, ThongKeFragment.this);
							}
						}
					};

					Thread thread = new Thread() {
						public void run() {
							JsonParser jParser = new JsonParser();
							String jobject = jParser.getURL(request
									.gettkdb(select));
							if (jobject != null) {
								Message msg = handler.obtainMessage(0, jobject);
								handler.sendMessage(msg);
							} else {
								String json = mPreference
										.getContentTKDB(select);
								if (!TextUtils.isEmpty(json)) {
									SmartLog.d("load old data from preference");
									Message msg = handler
											.obtainMessage(0, json);
									handler.sendMessage(msg);
								} else {
									Message msg = handler.obtainMessage(1);
									handler.sendMessage(msg);
								}
							}
						}
					};

					thread.start();
				}

			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	private void fillJsonToView(String json) {

		Parser_Tk parser = new Parser_Tk();
		arraylist = parser.getListTKDB(json);

		if (arraylist != null) {

			Collections.sort(arraylist, new ThongKeComparator());
			String number = "";

			if (select.equals("BO")) {
				for (Tk_Item item : arraylist) {
					number = item.getNumber();
					if (number != null) {
						if (number.length() == 1) {
							item.setNumber("0".concat(number));
						} else if (number.length() == 2) {
							break;
						}
					}
				}
			}

			ftkdb = (FragmentTKDB) _adapter.getItem(1);
			ftkdb.Load_data_webview_Tkdb(arraylist);
			_mViewPager.setCurrentItem(1);
			pdia.dismiss();
		} else {
			Util.showDialog(1, ThongKeFragment.this);
		}
	}

	private void initFragment() {
		Bundle rb = this.getIntent().getExtras();
		String json = rb.getString("json");
		posCurrent = rb.getInt("pos");
		System.out.println("POS CURRENT LÀ ===>>" + rb.getInt("pos"));
		if (posCurrent == 0) {
			ftkdb = (FragmentTKDB) FragmentTKDB.newInstance(this, posCurrent
					+ "", json, select);
			ftkn = (FragmentTKN) FragmentTKN.newInstance(this, posCurrent + "",
					json, matinh, name);
		} else if (posCurrent == 1) {
			ftkdb = (FragmentTKDB) FragmentTKDB.newInstance(this, posCurrent
					+ "", json, select);
			ftkn = (FragmentTKN) FragmentTKN.newInstance(this, posCurrent + "",
					json, matinh, name);
			first_text.setBackgroundResource(R.drawable.tk_tab1_2);
			second_text.setBackgroundResource(R.drawable.tk_tab2);
		}

		list_Fragment.add(ftkn);
		list_Fragment.add(ftkdb);
	}

	public void init_ViewPager() {

		FragmentManager fm = getSupportFragmentManager();
		_adapter = new KetQuaDetailAdapter(this, _mViewPager, fm, list_Fragment);
		_mViewPager.setAdapter(_adapter);
		_mViewPager.setCurrentItem(posCurrent);

		_mViewPager.setCurrentItem(0);
		first_text.setBackgroundResource(R.drawable.tk_tab1_2);
		second_text.setBackgroundResource(R.drawable.tk_tab2);
		tvTitle.setText("Thống Kê Nhanh");
	}

	private void setTab() {

		_mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int position) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					posCurrent = 0;
					ftkn = (FragmentTKN) _adapter.getItem(0);
					first_text.setBackgroundResource(R.drawable.tk_tab1_2);
					second_text.setBackgroundResource(R.drawable.tk_tab2);
					tvTitle.setText("Thống Kê Nhanh");
					_mViewPager.setCurrentItem(0);
					AddSpinnerTinh();
					break;
				case 1:
					posCurrent = 1;
					ftkdb = (FragmentTKDB) _adapter.getItem(1);
					first_text.setBackgroundResource(R.drawable.tk_tab1);
					second_text.setBackgroundResource(R.drawable.tk_tab2_2);
					tvTitle.setText("Thống Kê Đặc Biệt");
					_mViewPager.setCurrentItem(1);
					AddSpinnerTk();
					break;
				}
			}

		});
	}

	@Override
	public void onResume() {
		if (((MyApp) getApplication()).isKill()) {
			finish();
		}
		super.onResume();

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			System.out.println("THOAT NHE");
			quitDialog(ThongKeFragment.this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.first_text:
			posCurrent = 0;
			ftkn = (FragmentTKN) _adapter.getItem(0);
			first_text.setBackgroundResource(R.drawable.tk_tab1_2);
			second_text.setBackgroundResource(R.drawable.tk_tab2);
			tvTitle.setText("Thống Kê Nhanh");
			_mViewPager.setCurrentItem(0);
			AddSpinnerTinh();
			break;
		case R.id.second_text:
			posCurrent = 1;
			ftkdb = (FragmentTKDB) _adapter.getItem(1);
			first_text.setBackgroundResource(R.drawable.tk_tab1);
			second_text.setBackgroundResource(R.drawable.tk_tab2_2);
			tvTitle.setText("Thống Kê Đặc Biệt");
			_mViewPager.setCurrentItem(1);
			AddSpinnerTk();
			break;
		case R.id.tvSpTinh:
			sptinh.performClick();
			break;
		default:
			break;
		}
	}

	public void quitDialog(Context c) {

		dlquit = new Dialog(c);
		dlquit.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		dlquit.setTitle("Thoát ứng dụng ?");
		dlquit.setContentView(R.layout.dialog_quit);
		dlquit.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
		dlquit.getWindow().setBackgroundDrawable(
				new ColorDrawable(Color.rgb(50, 50, 50)));
		dlquit.getWindow().setTitleColor(XoSoConstants.White);
		dlquit.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon_registersc);

		Button huy = (Button) dlquit.findViewById(R.id.bthuy);
		huy.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				dlquit.dismiss();
			}
		});

		Button quit = (Button) dlquit.findViewById(R.id.btquit);
		quit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				((MyApp) getApplication()).setKill(true);
				finish();
				dlquit.dismiss();
			}
		});
		dlquit.show();
	}

	public class ThongKeComparator implements Comparator<Tk_Item> {
		@Override
		public int compare(Tk_Item object1, Tk_Item object2) {
			try {
				int number1 = Integer.valueOf(object1.getNumber());
				int number2 = Integer.valueOf(object2.getNumber());
				return (number1 - number2);
			} catch (ClassCastException ce) {
				return 1;
			}

		}
	}

}
